import axios from 'axios'
import { ElMessage } from 'element-plus';
import router from '@/router';
import {useTokenStore} from "@/stores/token.js";


const service = axios.create({
    baseURL:'http://localhost:8080'
});
//拦截器
service.interceptors.request.use(function(config) {
    const tokenStore = useTokenStore()
    //如果不是登录请求就要在请求头中添加token
    if(!config.url.startsWith ('/login')) {
        config.headers.token = tokenStore.tokenStr;
    }
    return config;
    //对请求错误做些什么
},function(error) {
    return Promise.reject(error);
});
//Axios响应拦截
service.interceptors.response.use(resp => {
    const tokenStore = useTokenStore()
    let token = resp.headers.token;
    tokenStore.update(token);
    return resp.data;
}, error => {
    if(error.status == 403){
        const tokenStore = useTokenStore()
        ElMessage({
            message: '令牌错误，请重新登录',
            dirstance: 1200,
            onClose: () => {
                //删除store中token
                tokenStore.$reset();
                //跳转到登录页面
                router.push('/login');
            }
        });
    }
    return Promise.reject(error);
});
export default service;